package com.gmldd.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;

public class JdbcUtil {
	private static String url = null;
	// 用户名
	private static String username = null;
	// 密码
	private static String password = null;
	private static String className = null;
	static {
		try {
			ResourceBundle bundle = ResourceBundle.getBundle("db.properties");

//			InputStream inStream = JdbcUtil.class.getResourceAsStream("db.properties");
//			//
//			Properties p = new Properties();
//			// 载入数据
//			p.load(inStream);
			url = bundle.getString("url");// 返回指定变量对应的值
			username = bundle.getString("username");
			password = bundle.getString("password");
			className = bundle.getString("className");
			// ①　注册驱动
			Class.forName(className);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取连接对象
	 *
	 * @return
	 */
	public static Connection getConnection() {
		// ②　创建连接 DriverManager负责获取连接
		// getConnection(url访问地址, user,用户 password密码)
		// Connection 应用程序与mysql数据库之间连接
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(url, username, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 关闭资源
	 *
	 * @param rs
	 * @param st
	 * @param conn
	 */
	public static void close(ResultSet rs, Statement st, Connection conn) {
		// 关闭结果集
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		// 关闭sql执行对象
		if (st != null) {
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		// 关闭连接对象
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

	}
}
